package com.shanhy.baseproject.common.redis;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Base64Utils;

/**
 * 注解式环境管理
 * 
 * @author   单红宇(CSDN catoop)
 * @create   2016年9月12日
 */
@Configuration
@EnableCaching
public class CachingConfig extends CachingConfigurerSupport {

	@Bean
	public KeyGenerator methodKeyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, Method method, Object... params) {
				StringBuilder sb = new StringBuilder();
				sb.append(target.getClass().getName());
				sb.append(method.getName());
				StringBuilder paramsSb = new StringBuilder();
				for (Object obj : params) {
					paramsSb.append((String)obj);
				}
				sb.append(Base64Utils.encodeToString(paramsSb.toString().getBytes()));
				return sb.toString();
			}
		};

	}
	
	/**
     * 管理缓存
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置缓存默认过期时间（全局的）
        // rcm.setDefaultExpiration(60);//秒
        //设置value的过期时间
        Map<String,Long> map=new HashMap<>();
        map.put("testCache",30L);// 秒
        rcm.setExpires(map);
        return rcm;
    }
}
